//Helps in creating a structure will help later.
function makeStruct(names) {
    var names = names.split(' ');
    var count = names.length;
    function constructor() {
        for (var i = 0; i < count; i++) {
            this[names[i]] = arguments[i];
        }
    }
    return constructor;
}

var rootcondition = '<table><tr><td class="seperator" ><img src="js/res/remove.png" alt="Remove" class="remove" /><select><option value="AND">Y</option><option value="OR">O</option></select></td>';
rootcondition += '<td class="group"><div class="querystmts"></div><div><img class="add" src="js/res/add.png" alt="Add" /> <img class="addroot" src="js/res/add-group.png" /></div>';
rootcondition += '</td></tr></table>';

var statement = '<div><img src="js/res/remove.png" alt="Remove" class="remove" />'

statement += '<select class="col">';
statement +='<option value="NOMBRE">NOMBRE</option>';
statement +='<option value="APELLIDO1">APELLIDO1</option>';
statement +='<option value="APELLIDO2">APELLIDO2</option>';
statement +='<option value="TIP_DOC">TIP_DOC</option>';
statement +='<option value="DOC_ID">DOC_ID</option>';
statement +='<option value="SEXO">SEXO</option>';
statement +='<option value="ESTADOCIVIL">ESTADOCIVIL</option>';
statement +='<option value="FECHA_NAC">FECHA_NAC</option>';
statement +='<option value="MUNICIPIO_NACIMIENTO">MUNICIPIO_NACIMIENTO</option>';
statement +='<option value="DEPARTAMENTO_NACIMIENTO">DEPARTAMENTO_NACIMIENTO</option>';
statement +='<option value="PAIS_NACIMIENTO">PAIS_NACIMIENTO</option>';
statement +='<option value="ACCESO">ACCESO</option>';
statement +='<option value="SUBACCESO">SUBACCESO</option>';
statement +='<option value="EMAIL">EMAIL</option>';
statement +='<option value="PAIS_RES">PAIS_RES</option>';
statement +='<option value="CIUDAD_RES">CIUDAD_RES</option>';
statement +='<option value="DIRECCION">DIRECCION</option>';
statement +='<option value="TELEFONO">TELEFONO</option>';
statement +='<option value="USERNAME">USERNAME</option>';
statement +='<option value="FECHA_GRADO">FECHA_GRADO</option>';
statement +='<option value="FECHA_INICIO">FECHA_INICIO</option>';
statement +='<option value="FECHA_FIN">FECHA_FIN</option>';
statement +='<option value="CODFACULTAD">CODFACULTAD</option>';
statement +='<option value="NOMBFACULTAD">NOMBFACULTAD</option>';
statement +='<option value="CODPROGRAMA">CODPROGRAMA</option>';
statement +='<option value="NOMBPROGRAMA">NOMBPROGRAMA</option>';
statement +='<option value="DIPLOMA">DIPLOMA</option>';
statement +='<option value="TITULOOBT">TITULOOBT</option>';
statement +='<option value="TITULOPROYECTO">TITULOPROYECTO</option>';
statement +='<option value="NIVEL">NIVEL</option>';
statement +='<option value="NOMBRE_NIVEL">NOMBRE_NIVEL</option>';
statement +='<option value="FECHA_GRADO_2">FECHA_GRADO_2</option>';
statement +='<option value="SEDE">SEDE</option>';
statement +='<option value="MANUAL">MANUAL</option>';
statement += '</select>';

statement += '<select class="op">';
statement += '<option value="=">Igual</option>';
statement += '<option value="<>">Diferente</option>';
statement += '<option value=">=">Mayor igual</option>';
statement += '<option value="<=">Menor igual</option>';
statement += '<option value="LIKE">Contiene</option>';
statement += '<option value="NOT LIKE">No contiene</option>';
statement += '</select>'

statement += '<input type="text" /></div>';

var addqueryroot = function (sel, isroot) {
    $(sel).append(rootcondition);
    var q = $(sel).find('table');
    var l = q.length;
    var elem = q;
    if (l > 1) {
        elem = $(q[l - 1]);
    }

    //If root element remove the close image
    if (isroot) {
        elem.find('td >.remove').detach();
    }
    else {
        elem.find('td >.remove').click(function () {
            // td>tr>tbody>table
            $(this).parent().parent().parent().parent().detach();
        });
    }

    // Add the default staement segment to the root condition
    elem.find('td >.querystmts').append(statement);

    // Add the head class to the first statement
    elem.find('td >.querystmts div >.remove').addClass('head');

    // Handle click for adding new statement segment
    // When a new statement is added add a condition to handle remove click.
    elem.find('td div >.add').click(function () {
        $(this).parent().siblings('.querystmts').append(statement);
        var stmts = $(this).parent().siblings('.querystmts').find('div >.remove').filter(':not(.head)');
        stmts.unbind('click');
        stmts.click(function () {
            $(this).parent().detach();
        });
    });

    // Handle click to add new root condition
    elem.find('td div > .addroot').click(function () {
        addqueryroot($(this).parent(), false);
    });
};


//Recursive method to parse the condition and generate the query. Takes the selector for the root condition
var getCondition = function (rootsel) {
    //Get the columns from table (to find a clean way to do it later) //tbody>tr>td
    var elem = $(rootsel).children().children().children();
    //elem 0 is for operator, elem 1 is for expressions

    var q = {};
    var expressions = [];
    var nestedexpressions = [];

    var operator = $(elem[0]).find(':selected').val();
    q.operator = operator;

    // Get all the expressions in a condition
    var expressionelem = $(elem[1]).find('> .querystmts div');
    for (var i = 0; i < expressionelem.length; i++) {
        expressions[i] = {};
        var col = $(expressionelem[i]).find('.col :selected');
        var op = $(expressionelem[i]).find('.op :selected');
        expressions[i].colval = col.val();
        expressions[i].coldisp = col.text();
        expressions[i].opval = op.val();
        expressions[i].opdisp = op.text();
		
		var valtemp = $(expressionelem[i]).find(':text').val();
		if ($.trim(valtemp) =='')
			expressions[i].val = "NULL";
		else if (op.val() =='LIKE' || op.val() == 'NOT LIKE')
			expressions[i].val = "'%" + valtemp + "%'";
		else
			expressions[i].val = "'" + valtemp + "'";
    }
    q.expressions = expressions;

    // Get all the nested expressions
    if ($(elem[1]).find('table').length != 0) {
        var len = $(elem[1]).find('table').length;

        for (var k = 0; k < len; k++) {
            nestedexpressions[k] = getCondition($(elem[1]).find('table')[k]);
        }
    }
    q.nestedexpressions = nestedexpressions;

    return q;
};

//Recursive method to iterate over the condition tree and generate the query
var getQuery = function (condition) {
    var op = [' ', condition.operator, ' '].join('');

    var e = [];
    var elen = condition.expressions.length;
    for (var i = 0; i < elen; i++) {
        var expr = condition.expressions[i];
        e.push(expr.colval + " " + expr.opval + " " + expr.val);
    }

    var n = [];
    var nlen = condition.nestedexpressions.length;
    for (var k = 0; k < nlen; k++) {
        var nestexpr = condition.nestedexpressions[k];
        var result = getQuery(nestexpr);
        n.push(result);
    }

    var q = [];
    if (e.length > 0)
        q.push(e.join(op));
    if (n.length > 0)
        q.push(n.join(op));

    return ['(', q.join(op), ')'].join(' ');
};

